package com.zipking.cloud.springbootmybatis.util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.support.TransactionTemplate;
@Slf4j
@Component
public class TransactionUtil {

    private static TransactionTemplate transactionTemplate;

    @Autowired
    public void setTransactionTemplate(TransactionTemplate transactionTemplate) {
        TransactionUtil.transactionTemplate = transactionTemplate;
    }

    /**
     * 事务执行
     * @param callback
     * @return
     */
    public static boolean execute(Fn<Boolean> callback){
        transactionTemplate.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ);
        transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
        transactionTemplate.setTimeout(5000);
        transactionTemplate.setReadOnly(false);
        Boolean rs = transactionTemplate.execute(status -> {
            try {
                return callback.run();
            } catch (Exception e) {
                status.setRollbackOnly();
                log.info("事务异常:{}", e);
                return false;
            }
        });
        return rs != null && rs;
    }

    @FunctionalInterface
    public interface Fn<T>{
        T run();
    }
}
